package com.yz.pay.mq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.yz.common.constant.MQConstants;
import com.yz.common.properties.RabbitMqProperties;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.TimeoutException;
/**
 * Created With IntelliJ IDEA.
 * Descriptions:
 * <p>
 * User:Mr.Du
 * Date:2024/4/9
 * Time:15:12
 */
@Slf4j
@Component
public class MqInitMain {

    @Resource
    private RabbitMqProperties rabbitMqProperties;

    @PostConstruct
    public void mqInitMain(){
        Channel channel = null;
        try{
            log.info("rabbitMqProperties:{}", rabbitMqProperties);
            ConnectionFactory factory = new ConnectionFactory();
            factory.setHost(rabbitMqProperties.getHost());
            factory.setPort(rabbitMqProperties.getPort());
            factory.setUsername(rabbitMqProperties.getUsername());
            factory.setPassword(rabbitMqProperties.getPassword());
            Connection connection = factory.newConnection();
            channel = connection.createChannel();
            initMq(channel, MQConstants.PAY_EXCHANGE_NAME, MQConstants.PAY_QUEUE_NAME, MQConstants.PAY_ROUTING_KEY);
            initMq(channel, MQConstants.PROMOTION_EXCHANGE_NAME, MQConstants.PROMOTION_QUEUE_NAME, MQConstants.PROMOTION_ROUTING_KEY);
            initMq(channel, MQConstants.BI_EXCHANGE_NAME, MQConstants.BI_QUEUE_NAME, MQConstants.BI_ROUTING_KEY);
            initMq(channel, MQConstants.USER_EXCHANGE_NAME, MQConstants.USER_QUEUE_NAME, MQConstants.USER_ROUTING_KEY);
            initMq(channel, MQConstants.ORDER_EXCHANGE_NAME, MQConstants.ORDER_QUEUE_NAME, MQConstants.ORDER_ROUTING_KEY);
        }catch (Exception e){
            throw  new RuntimeException(e);
        } finally {
            try {
                channel.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            } catch (TimeoutException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public static void initMq(Channel channel, String exchangeName, String queueName, String routingKey){
        try {
            channel.exchangeDeclare(exchangeName, "direct");
            channel.queueDeclare(queueName, true, false, false, null);
            channel.queueBind(queueName, exchangeName, routingKey);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}
